package hos.demo

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import hos.demo.databinding.FragmentFirstBinding

/**
 * A simple [Fragment] subclass as the default destination in the navigation.
 */
class FirstFragment : Fragment() {

    private var _binding: FragmentFirstBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    private val mViewModel by activityViewModels<MainViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d("Thread", "onCreate: FirstFragment")
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View? {
        Log.d("Thread", "onCreateView: FirstFragment")
        _binding = FragmentFirstBinding.inflate(inflater, container, false)
        return binding.root

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.buttonStart.setOnClickListener {
            startActivity(Intent(requireActivity(), LifecycleHandlerActivity::class.java))
        }

        binding.buttonFirst.setOnClickListener {
            findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment)
        }
        Log.d("Thread", "onViewCreated: FirstFragment")
        Log.d("Thread", "onViewCreated: FirstFragment $binding")
        // 进度监听回调
        mViewModel.progress
            .onProgress {
                Log.d("Thread", "onProgress: FirstFragment $this")
                binding.progress.progress = this.toInt()
            }.onCatch {
                Log.d("Thread", "onCatch: FirstFragment")
                this.printStackTrace()
            }.onSuccess {
                binding.progressLive.progress = 100
                Log.d("Thread", "onSuccess: FirstFragment")
            }

        mViewModel.progressLive
            .onProgress {
                Log.d("Thread", "onProgress:Live FirstFragment $this")
                binding.progressLive.progress = this.toInt()
            }.onCatch {
                Log.d("Thread", "onCatch:Live FirstFragment")
                this.printStackTrace()
            }.onSuccess {
                binding.progressLive.progress = 100
                Log.d("Thread", "onSuccess:Live FirstFragment")
            }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        Log.d("Thread", "onDestroyView: FirstFragment")
        _binding = null
    }
}